#pragma once


#include<assert.h>
#include<iostream>

using namespace std;

namespace yyh
{
	template<class K, class V>
	struct AVLTreeNode
	{
		pair<K, V> _kv;
		AVLTreeNode<K, V>* _left;
		AVLTreeNode<K, V>* _right;
		AVLTreeNode<K, V>* _parent;
		int _bf;

		AVLNode(const pair<K, V> kv)
			:_kv(kv)
			, _left(nullptr)
			, _right(nullptr)
			, _parent(nullptr)
			, _bf(0)
		{ }
	};

	template<class K, class V>
	class AVLTree
	{
		typedef AVLTreeNode<K, V> Node;
	public:
		void RotateR(Node* parent)
		{
			Node* sub_left = parent->_left;
			Node* sub_left_right = sub_left->_right;

			parent->_left = sub_left_right;
			sub_left->_right = parent;

			if (sub_left_right)
			{
				sub_left_right->_parent = parent;
			}

			Node* parent_parent = parent->_parent;
			parent->_parent = sub_left;

			if (parent == _root)
			{
				_root = sub_left;
				sub_left->_parent = nullptr;
			}
			else
			{
				if (parent_parent->_left == parent)
				{
					parent_parent->_left = sub_left;
				}
				else
				{
					parent_parent->_right = sub_left;
				}

				sub_left->_parent = parent_parent;
			}

			sub_left->_bf = parent->_bf = 0;
		}

		bool insert(const pair<K, V> kv)
		{
			if (_root == nullptr)
			{
				_root = new Node(kv);
				return true;
			}

			Node* cur = _root;
			Node* parent = nullptr;

			while (cur)
			{
				if (kv.first > cur->_kv.first)
				{
					parent = cur;
					cur = cur->_right;
				}
				else if (kv.first < cur->_kv.first)
				{
					parent = cur;
					cur = cur->_left;
				}
				else
				{
					return false;
				}
			}

			cur = new Node(kv);
			if (kv.first > parent->_kv.first)
			{
				parent->_right = cur;
			}
			else
			{
				parent->_left-> = cur;
			}
			cur->_parent = parent;

			while (parent)
			{
				if (cur == parent->_left)
				{
					parent->_bf--;
				}
				else
				{
					parent->_bf++;
				}

				if (parent->_bf == 0)
				{
					break;
				}
				else if (parent->_bf == 1 || parent->_bf == -1)
				{
					cur = parent;
					parent = parent->_parent;
				}
				else if (parent->_bf == 2 || parent->_bf == -2)
				{
					if (parent->_bf == -2 && cur->_bf == -1)
					{
						RotateR(parent);
					}
					else if (parent->_bf == 2 && cur->_bf == 1)
					{

					}
					break;
				}
				else
				{
					assert(false);
				}
			}
		}

	private:
		Node* _root = nullptr;
	};
}